package com.itheima.controller;

import com.itheima.pojo.Items;
import com.itheima.service.ItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;

/**
 * @Author a2687
 * @create 2021/9/13 18:02
 */
@Controller
@RequestMapping("/items")
public class ItemsCtrollerImpl {
    @Autowired
    private ItemsService itemsService;
    @RequestMapping("/list")
    public String list(Model model){
        List<Items> all=itemsService.findAll();
        model.addAttribute("items",all);
        return "items";

    }
    @RequestMapping("/save")
    public ModelAndView save(@Valid Items items,Errors errors,Model model){
        ModelAndView modelAndView=new ModelAndView();
        /*if(errors.hasErrors()){
            List<FieldError> fieldErrors=errors.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                String field=fieldError.getField();
                String defaultMessage=fieldError.getDefaultMessage();
                modelAndView.addObject(field,defaultMessage);

            }
        }else{

            int save=itemsService.save(items);
        }*/
        int save=itemsService.save(items);
        List<Items> all=itemsService.findAll();
        modelAndView.addObject("items",all);
        modelAndView.setViewName("items");
        return modelAndView;

    }
}
